﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Configuration;

namespace Subsidiary.CouponWrapper
{
    public class CouponFacade
    {
        public static void PickUp(string siteCode, string html)
        {
            ICouponWrapper couponWrapper = CouponWrapperFactory.Create(siteCode);
            html = html.Trim().Replace("\r", "").Replace("\n", "");
            List<CouponItem> coupons = couponWrapper.PickUp(html);
            foreach (CouponItem coupon in coupons)
            {
                InsertCoupon(coupon);
            }
        }

        public static void InsertCoupon(CouponItem coupon)
        {
            string folder = ConfigurationManager.AppSettings["DataFolder"];
            if (!Directory.Exists(string.Format("{0}coupons", folder)))
            {
                Directory.CreateDirectory(string.Format("{0}coupons", folder));
            }

            var fileName = string.Format("{0}coupons{1}{2}.xml", folder, Path.DirectorySeparatorChar, coupon.Id);
            var settings = new XmlWriterSettings { Indent = true };
            var ms = new MemoryStream();

            using (var writer = XmlWriter.Create(ms, settings))
            {
                writer.WriteStartDocument(true);
                writer.WriteStartElement("coupon");

                writer.WriteElementString("title", coupon.Title);
                writer.WriteElementString("shop", coupon.Shop);
                writer.WriteElementString("link", coupon.Link);
                writer.WriteElementString("endDate", coupon.EndDate);
                writer.WriteElementString("number", coupon.Number);
                writer.WriteElementString("password", coupon.Password);
                writer.WriteElementString("amount", coupon.Amount.ToString());
                writer.WriteElementString("comment", coupon.Comment);
                writer.WriteEndElement();
            }

            using (var fs = File.Open(fileName, FileMode.Create, FileAccess.Write))
            {
                ms.WriteTo(fs);
                ms.Dispose();
            }
        }
    }
}
